import { login } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: JSON.parse(localStorage.getItem('user')) || {}
}
const mutations = {
  setToken(state, val) {
    // 保存到vuex
    state.token = val.token.token
    // 保存到cookie
    setToken(val.token.token)

    // 获取用户信息
    state.userInfo = val.user
    console.log(val.user.name)
    // 存储到本地
    localStorage.setItem('user', JSON.stringify(val.user))
  },
  // 清空token
  logout(state, val) {
    state.token = ''
    removeToken()
    state.userInfo = ''
  }

}
const actions = {
  // 登录
  async login(context, payload) {
    const res = await login(payload)
    // console.log(res)
    // 传给mutations
    context.commit('setToken', res.data.data)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

